//
//  YYLYCarouselView.m
//  LaiyunCommunity
//
//  Created by YYKJ on 2020/8/13.
//  Copyright © 2020 易云物联. All rights reserved.
//

#import "YYLYCarouselView.h"
#import "JPVideoPlayerKit.h"
#import <UIImageView+WebCache.h>
#import "SHCommonDefines.h"
#import "XXExtension.h"


@implementation YYLYCarouselViewCell

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.contentImageView = ({
            UIImageView *videoPlayerView = [UIImageView new];
            videoPlayerView.contentMode = UIViewContentModeScaleAspectFill;
            videoPlayerView.clipsToBounds = YES;
            [self.contentView addSubview:videoPlayerView];

            videoPlayerView;
        });

    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.contentImageView.frame = self.bounds;
}

@end


@interface YYLYCarouselView () <JPScrollViewPlayVideoDelegate, UIScrollViewDelegate, JPVideoPlayerDelegate>

@property (nonatomic, weak) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, assign) NSInteger totalItemsCount;

@property (nonatomic, strong) UIScrollView *mainScrollView;
@property (nonatomic, strong) UIImage *placeholderImage;
@property (nonatomic, strong) YYLYCarouselViewCell *firstVideoCell;
@property (nonatomic, strong) UILabel *cycleIndexLabel; // 图片索引标签
@property (nonatomic, assign) NSInteger currentImageIndex; // 当前对应索引

@end


@implementation YYLYCarouselView

- (void)dealloc {
    _collectionView.delegate = nil;
    _collectionView.dataSource = nil;
    
    if (_firstVideoCell.jp_videoPlayView) {
        [_firstVideoCell.jp_videoPlayView jp_stopPlay];
    }
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self initialization];
        [self setupMainView];
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self initialization];
    [self setupMainView];
}

- (void)initialization
{
    self.currentImageIndex = 0;
    self.placeholderImage = [UIImage imageNamed:@""];
}

// 设置显示图片的collectionView
- (void)setupMainView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    _flowLayout = flowLayout;
        
    UIScrollView *mainScrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
    mainScrollView.pagingEnabled = YES;
    mainScrollView.userInteractionEnabled = YES;
    mainScrollView.delegate = self;
    [self addSubview:mainScrollView];
    self.mainScrollView = mainScrollView;
    
    // 右下角索引标签
    NSString *title = [NSString stringWithFormat:@"--/--"];
    UILabel *indexLabel = [UILabel xx_labelWithText:title textColor:UIColor.whiteColor font:[UIFont systemFontOfSize:10] backgroundColor:UIColor.lightGrayColor];
    indexLabel.frame = CGRectMake(DEVICE_WIDTH - 34 - 12, self.height - 16 - 12, 34, 16);
    indexLabel.layer.cornerRadius = 8;
    indexLabel.layer.masksToBounds = YES;
    indexLabel.textAlignment = NSTextAlignmentCenter;
    self.cycleIndexLabel = indexLabel;
    [self addSubview:indexLabel];
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _flowLayout.itemSize = self.frame.size;
    _collectionView.jp_scrollViewVisibleFrame = self.bounds;
}

- (NSInteger)currentIndex {
    if (_collectionView.width == 0 || _collectionView.width == 0) {
        return 0;
    }
    
    int index = 0;
    if (_flowLayout.scrollDirection == UICollectionViewScrollDirectionHorizontal) {
        index = (_collectionView.contentOffset.x + _flowLayout.itemSize.width * 0.5) / _flowLayout.itemSize.width;
    }
    
    return MAX(0, index);
}

- (int)pageControlIndexWithCurrentCellIndex:(NSInteger)index
{
    return (int)index % self.sourceArray.count;
}

- (BOOL)isMp4:(NSString *)sourceUrl {
    BOOL result = NO;
    if ([sourceUrl hasSuffix:@"mp4"] && [sourceUrl hasPrefix:@"http"]) {
        result = YES;
    }
    return result;
}


#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (!self.sourceArray.count) return; // 解决清除timer时偶尔会出现的问题
//    CGFloat itemIndex = [self currentIndex];
//    int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:itemIndex];
    
    [self.collectionView jp_scrollViewDidScroll];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.collectionView jp_scrollViewDidEndDraggingWillDecelerate:decelerate];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self.collectionView jp_scrollViewDidEndDecelerating];
    [self scrollViewDidEndScrollingAnimation:self.collectionView];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    if (!self.sourceArray.count) return;
    
    CGFloat itemIndex = [self currentIndex];
    _currentImageIndex = itemIndex;
    
    int indexOnPageControl = [self pageControlIndexWithCurrentCellIndex:itemIndex];
    NSString *imagePath = self.sourceArray[indexOnPageControl];

    self.cycleIndexLabel.text = [NSString stringWithFormat:@"%d/%lu", indexOnPageControl+1, (unsigned long)self.sourceArray.count];
}

#pragma mark - JPScrollViewPlayVideoDelegate

- (void)scrollView:(UIScrollView<JPVideoPlayerScrollViewProtocol> *)scrollView willPlayVideoOnCell:(UIView<JPVideoPlayerCellProtocol>  *)cell {

}

#pragma mark - JPVideoPlayerDelegate

- (BOOL)shouldAutoReplayForURL:(nonnull NSURL *)videoURL {
    return NO;
}

- (void)playerStatusDidChanged:(JPVideoPlayerStatus)playerStatus {}

#pragma mark - Setter & getter
- (void)setSourceArray:(NSArray *)sourceArray {
    _sourceArray = sourceArray;
    _totalItemsCount = sourceArray.count;
    
    self.cycleIndexLabel.text = [NSString stringWithFormat:@"1/%lu", (unsigned long)self.sourceArray.count];
    self.mainScrollView.contentSize = CGSizeMake(self.sourceArray.count*self.frame.size.width, self.frame.size.height);

    for (int i = 0; i < self.sourceArray.count; i ++) {
        NSString *imagePath = self.sourceArray[i];
            if ([self isMp4:imagePath]) {
                NSURL *url = [NSURL URLWithString:self.sourceArray[0]];
                self.mainScrollView.jp_videoPlayerDelegate = self;
                [self.mainScrollView jp_playVideoWithURL:url
                                      bufferingIndicator:nil
                                             controlView:nil
                                            progressView:nil
                                           configuration:nil];
            } else { // 图片
                UIImageView * img = [[UIImageView alloc]initWithFrame:CGRectMake(i*self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
                [img sd_setImageWithURL:[NSURL URLWithString:self.sourceArray[i]] placeholderImage:self.placeholderImage];
                img.userInteractionEnabled = YES;
                [self.mainScrollView addSubview:img];
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgTapClick)];
                [img addGestureRecognizer:tap];
            }
        }
    
//    _collectionView.scrollEnabled = _totalItemsCount > 1;
//    [_collectionView jp_handleCellUnreachableTypeInVisibleCellsAfterReloadData];
//    [_collectionView jp_playVideoInVisibleCellsIfNeed];
//    [_collectionView reloadData];
}

#pragma mark - Event response
- (void)imgTapClick {
    if ([self.delegate respondsToSelector:@selector(yyly_carouselView:didClickIndex:)]) {
        [self.delegate yyly_carouselView:self didClickIndex:_currentImageIndex];
    }
}

#pragma mark - Convenice method

@end
